package cn.zjweu.dao.impl;

import cn.zjweu.dao.CartDao;
import cn.zjweu.domain.Dish;
import cn.zjweu.domain.MessageInfo;
import cn.zjweu.domain.UserCart;
import cn.zjweu.utils.JDBCUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class CartDaoImpl implements CartDao {
    private Connection conn;
    private PreparedStatement pst;
    private ResultSet rs;

    private void initThree() throws SQLException {
        conn = JDBCUtil.getConnection();
        pst = null;
        rs = null;
    }

    private void initTwo() throws SQLException {
        conn = JDBCUtil.getConnection();
        pst = null;
    }

    @Override
    public UserCart findCartByUserAndDish(int userId, int dishId) {
        UserCart userCart = new UserCart(userId, dishId);
        String sql = "SELECT * FROM userCart WHERE userId = ? AND dishId = ?";

        try {
            initThree();
            pst = conn.prepareStatement(sql);
            pst.setInt(1, userId);
            pst.setInt(2, dishId);
            System.out.println(pst.toString());
            rs = pst.executeQuery();
            int lineCount = 0;

            while (rs.next()) {
                userCart.setCount(rs.getInt("count"));
                lineCount++;
            }
            if (lineCount < MessageInfo.MIN_UPDATE_LINE)
                return null;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.close(rs, pst, conn);
        }
        return userCart;
    }

    @Override
    public boolean editCountInCart(UserCart userCart) {
        String sql = "UPDATE userCart SET count = ? WHERE userId = ? AND dishId = ?";
        try {
            initTwo();
            pst = conn.prepareStatement(sql);
            pst.setInt(1, userCart.getCount());
            pst.setInt(2, userCart.getUserId());
            pst.setInt(3, userCart.getDishId());
            System.out.println(pst.toString());
            if (pst.executeUpdate() < MessageInfo.MIN_UPDATE_LINE) {
                return MessageInfo.FAIL;
            }
        } catch (SQLException e) {
            return MessageInfo.FAIL;
        } finally {
            JDBCUtil.close(pst, conn);
        }
        return MessageInfo.SUCCESS;
    }

    @Override
    public boolean saveToCart(UserCart userCart) {
        String sql = "INSERT INTO userCart VALUES(?,?,?)";
        try {
            initTwo();
            pst = conn.prepareStatement(sql);
            pst.setInt(1, userCart.getUserId());
            pst.setInt(2, userCart.getDishId());
            pst.setInt(3, userCart.getCount());
            System.out.println(pst.toString());
            if (pst.executeUpdate() < MessageInfo.MIN_UPDATE_LINE) {
                return MessageInfo.FAIL;
            }
        } catch (SQLException e) {
            return MessageInfo.FAIL;
        } finally {
            JDBCUtil.close(pst, conn);
        }
        return MessageInfo.SUCCESS;
    }

    @Override
    public boolean clearCartByUserIdOrDishId(int userId, int dishId) {
        String sql = "DELETE FROM userCart WHERE userId = ?";
        StringBuilder sb = new StringBuilder(sql);
        if (dishId != 0) {
            sb.append(" AND  dishId = ?");
        }
        try {
            initTwo();
            pst = conn.prepareStatement(sb.toString());
            pst.setInt(1, userId);
            if (dishId != 0)
                pst.setInt(2, dishId);
            System.out.println(pst);
            pst.executeUpdate();
        } catch (SQLException e) {
            return MessageInfo.FAIL;
        } finally {
            JDBCUtil.close(pst, conn);
        }
        return MessageInfo.SUCCESS;
    }

    @Override
    public List<Dish> findCartListByUserId(int userId) {
//        String sql = "SELECT * FROM dish WHERE dishId IN(SELECT dishId FROM userCart WHERE userId = ?)";
        String sql = "SELECT * FROM " +
                "(SELECT * FROM dish WHERE dishId IN(SELECT dishId FROM userCart WHERE userId = ?)) s, " +
                "userCart uc WHERE s.dishId = uc.dishId AND userId = ?";
        List<Dish> dishList = new ArrayList<>();
        try {
            initThree();
            pst = conn.prepareStatement(sql);
            pst.setInt(1, userId);
            pst.setInt(2, userId);
            System.out.println(pst);
            rs = pst.executeQuery();
            while (rs.next()) {
                Dish dish = new Dish();
                dish.setDishId(rs.getInt("dishId"));
                dish.setDishName(rs.getString("dishName"));
                dish.setDishPrice(rs.getBigDecimal("disPrice"));
                dish.setImagesRoute(rs.getString("imagesRoute"));
                dish.setCount(rs.getInt("count"));
                dish.setStatus(false);
                dishList.add(dish);
            }
        } catch (SQLException e) {
            return null;
        } finally {
            JDBCUtil.close(rs, pst, conn);
        }
        return dishList;
    }

    @Override
    public boolean clearCartByUserId(int userId) {
        String sql = "DELETE FROM userCart WHERE userId = ?";
        try {
            initTwo();
            pst = conn.prepareStatement(sql);
            pst.setInt(1, userId);
            System.out.println(pst);
            pst.executeUpdate();
        } catch (SQLException e) {
            return MessageInfo.FAIL;
        } finally {
            JDBCUtil.close(pst, conn);
        }
        return MessageInfo.SUCCESS;
    }

    @Override
    public boolean delByUserIdAndDList(Integer userId, String delCart) {
        StringBuilder sql = new StringBuilder("DELETE FROM userCart WHERE userId = ? AND dishId IN (");
        int i = 2;
        String[] cartsStr = delCart.split(",");
        List<Integer> params = new ArrayList<>();

        for (String str : cartsStr) {
            if (i == 2) sql.append("?");
            else sql.append(",?");
            params.add(Integer.valueOf(str));
            i++;
        }
        sql.append(")");
        try {
            initTwo();
            pst = conn.prepareStatement(sql.toString());
            pst.setInt(1, userId);
            while (i > 2) {
                pst.setInt(i-1, params.get(i - 3));
                i--;
            }
            System.out.println(pst);
            pst.executeUpdate();
        } catch (SQLException e) {
            return MessageInfo.FAIL;
        } finally {
            JDBCUtil.close(pst, conn);
        }
        return MessageInfo.SUCCESS;
    }
}
